package com.ldg.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.ld.utils.PageUtils;
import com.ldg.manager.entity.ContentCategoryEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ld.utils.Query;

import com.ldg.manager.dao.ContentDao;
import com.ldg.manager.entity.ContentEntity;
import com.ldg.manager.service.ContentService;

import javax.annotation.Resource;


@Service("contentService")
public class ContentServiceImpl extends ServiceImpl<ContentDao, ContentEntity> implements ContentService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ContentEntity> page = this.page(
                new Query<ContentEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public void insert(ContentEntity content) {
        //清理缓存
        stringRedisTemplate.delete("contentList");
        //添加
        baseMapper.insert(content);
    }

    @Override
    public void update(ContentEntity content) {
        stringRedisTemplate.delete("contentList");
        //修改
        baseMapper.updateById(content);
    }

    @Override
    public void delByIds(String[] ids) {
        stringRedisTemplate.delete("contentList");
        //删除
        for (String id : ids) {
            baseMapper.deleteById(id);
        }
    }

    @Override
    public List<ContentEntity> findContentListByCategoryId(int id) {
        List<ContentEntity> contentEntities;
        String contentList = stringRedisTemplate.opsForValue().get("contentList");
        if (StringUtils.isNotBlank(contentList)) {
            contentEntities = JSON.parseArray(contentList, ContentEntity.class);
            return contentEntities;
        } else {
            System.out.println("数据发生改动，正在和数据库同步^_^");
            contentEntities = baseMapper.selectList(new QueryWrapper<ContentEntity>().eq("category_id", id));
            stringRedisTemplate.opsForValue().set("contentList", JSON.toJSONString(contentEntities));
        }
        return contentEntities;
    }

}
